import { Button, Space } from "@douyinfe/semi-ui";
import React, { useRef } from "react";
import CancelToken from "./cancelToken";

const CancelTokenApp: React.FC = () => {
  const cancelCallbackRef = useRef<(value: void | PromiseLike<void>) => void>();

  const cancellableDelayedResolve = (delay: number) => {
    setTimeout(console.log, 0, "set delay");

    return new Promise<void>((resolve, reject) => {
      const id = setTimeout(() => {
        setTimeout(console.log, 0, "delayed resolved");
        resolve();
      }, delay);

      const cancelToken = new CancelToken(cancelCallback => {
        cancelCallbackRef.current = cancelCallback;
      });

      cancelToken.promise.then(() => clearTimeout(id));
    });
  };

  const start = () => {
    cancellableDelayedResolve(2000);
  };

  const cancel = () => {
    cancelCallbackRef.current?.();
  };

  return (
    <>
      <h3>CancelToken</h3>
      <Space spacing={20}>
        <Button onClick={start}>开始</Button>
        <Button onClick={cancel}>取消</Button>
      </Space>
    </>
  );
};
export default CancelTokenApp;
